package com.syedu.day16;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * description：文件拷贝
 * @author Administrator
 * @date 2022/4/6 15:32
 */
public class FileCopyDemo {
    public static void main(String[] args) {
        //方式一:
        copyFile("D:\\阿里巴巴Java开发手册终极版v1.3.0.pdf", "D:\\java学习\\alibaba.pdf");

        //方式二:第三方工具类
        //FileUtil.copyFile("D:\\阿里巴巴Java开发手册终极版v1.3.0.pdf", "D:\\java学习\\alibaba.pdf");
        //FileUtil.copyFile("D:\\阿里巴巴Java开发手册终极版v1.3.0.pdf", "D:\\java学习\\alibaba.pdf", StandardCopyOption.REPLACE_EXISTING);
    }

    /**
     * 文件拷贝
     */
    public static void copyFile(String src, String target) {
        //注意:此方式由于每次读取一个字节,写入一个字节,所以效率较低,例如当前拷贝的文件一共105万个字节,则读写就要105万*2,性能太差
        /*//1.根据源头和目标选择相应的IO流
        try (InputStream inputStream = new FileInputStream(src);
             OutputStream outputStream = new FileOutputStream(target)) {
            int len = -1;
            //2.循环读取
            while ((len = inputStream.read()) != -1) {
                //3.循环写
                outputStream.write(len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        /**
         * 使用带缓存的IO流来提高程序的读写性能
         *
         * InputStream inputStream = new FileInputStream(src) ==> BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(src));
         *  OutputStream outputStream = new FileOutputStream(target) ==> BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target));
         */
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(src));
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target))) {
            int len = -1;
            //定义缓冲大小
            byte[] buf = new byte[3 * 1024];//3k
            //读取一个缓冲大小的数据
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}